﻿using System;
using System.Collections.Generic;
using GolSig.Library;

namespace GolSig.WPF
{
    public class MainWindowPresenter
    {
        private readonly IMainWindow _view;

        private BoardSize _boardSize;
        private Game _gameOfLife;


        public MainWindowPresenter(IMainWindow view)
        {
            _view = view;
        }

        public void Initialize()
        {
            _boardSize = _view.GetBoardSize();

            _gameOfLife = new Game(_boardSize);

            _view.SetupGrid();

            var lifeOnes = GetLifeOnes(1000);

            _gameOfLife.Initialize(lifeOnes);

            _view.ShowGridContent(_gameOfLife.Cells());
        }

        public void Step()
        {
            _view.StopTimer();

            _gameOfLife.Next();

            _view.ShowGridContent(_gameOfLife.Cells());
        }


        private IEnumerable<CellInfo> GetLifeOnes(int max)
        {
            var lifeOnes = new List<CellInfo>();
            var r = new Random();

            for (int i = 0; i < max; i++)
            {
                lifeOnes.Add(new CellInfo(new Position(r.Next(_boardSize.Rows), r.Next(_boardSize.Columns)), true));
            }
            return lifeOnes.ToArray();
        }


        internal void Animate()
        {
            _view.StartTimer();
        }

        internal void Randomize()
        {
            _view.StopTimer();

            var lifeOnes = GetLifeOnes(1000);

            _gameOfLife.Initialize(lifeOnes);

            _view.ShowGridContent(_gameOfLife.Cells());
        }

        internal void NextState()
        {
            _gameOfLife.Next();

            _view.ShowGridContent(_gameOfLife.Cells());
        }
    }
}